package com.cqjtu.eecs.utils.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cqjtu.eecs.entity.TrainingGoalBriefEntity;
import com.cqjtu.eecs.entity.TrainingProject;
import com.cqjtu.eecs.entity.dto.TrainingProjectDTO;
import com.cqjtu.eecs.service.ITrainingGoalBriefEntityService;
import com.cqjtu.eecs.service.ITrainingProjectService;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class TrainingProjectListener extends AnalysisEventListener<TrainingProjectDTO> {
    private ITrainingProjectService trainingProjectService;
    private ITrainingGoalBriefEntityService trainingGoalBriefEntityService;

    private List<TrainingProjectDTO> list;


    public TrainingProjectListener(ITrainingProjectService trainingProjectService, ITrainingGoalBriefEntityService trainingGoalBriefEntityService){
        this.trainingGoalBriefEntityService = trainingGoalBriefEntityService;
        this.trainingProjectService = trainingProjectService;
        list = new ArrayList<>();
    }

    @Override
    public void invoke(TrainingProjectDTO trainingProjectDTO, AnalysisContext analysisContext) {
        if (trainingProjectDTO.getVersionCode()!= null)
            list.add(trainingProjectDTO);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //sheet0只有一条数据，读取sheet0中的并转换为数据库中的实体然后存入数据库。
        TrainingProjectDTO trainingProjectDTO = list.get(0);
        TrainingProject trainingProject = new TrainingProject(trainingProjectDTO);
        TrainingGoalBriefEntity trainingGoalBriefEntity = new TrainingGoalBriefEntity(trainingProjectDTO);
        // 如果专业存在模板则先删除
        TrainingProject trainingProject1 = trainingProjectService.getOne(new LambdaQueryWrapper<TrainingProject>()
                .eq(TrainingProject::getMajorCode, list.get(0).getMajorCode()));
        if (trainingProject != null){
            trainingProjectService
                    .remove(new LambdaUpdateWrapper<TrainingProject>()
                            .eq(TrainingProject::getMajorCode, list.get(0).getMajorCode()));
        }
        trainingProjectService.save(trainingProject);
        trainingGoalBriefEntityService.save(trainingGoalBriefEntity);
    }
}
